from fastapi import APIRouter,HTTPException,Query
from fastapiApp.schemas.base_scheams import Fail, Success, SuccessExtra
from fastapiApp.controllers.task_control import task_manager

# 创建任务管理路由
router = APIRouter()

@router.get("/status", summary="获取进程状态")
async def get_task_status(task_name: str = Query(..., description="进程name")):
    if task_name not in task_manager.tasks:
        raise HTTPException(status_code=404, detail="任务不存在")
    data={"task_name": task_name,
        **task_manager.get_task_details(task_name)}
    return Success(data=data)

@router.get("/allstatus", summary="获取所有进程")
async def get_all_tasks_status():
    data_list = [
        {
            "task_name": task_name,
            ** task_manager.get_task_details(task_name)
        }
        for task_name in task_manager.tasks.keys()
    ]
    return Success(data=data_list)

@router.post("/start", summary="启动进程")
async def start_task(task_name: str = Query(..., description="进程name")):
    if task_name not in task_manager.tasks:
        raise HTTPException(status_code=404, detail="任务不存在")

    result = await task_manager.start_task(task_name)
    data =  {
        "task_name": task_name,
        "status": "已启动" if result else "已在运行中",
        "current_status": task_manager.tasks[task_name].status
    }
    return Success(data=data)

@router.post("/stop", summary="停止进程")
async def stop_task(task_name: str = Query(..., description="进程name")):
    if task_name not in task_manager.tasks:
        raise HTTPException(status_code=404, detail="任务不存在")

    result = await task_manager.stop_task(task_name)
    data =  {
        "task_name": task_name,
        "status": "已停止" if result else "未在运行中",
        "current_status": task_manager.tasks[task_name].status
    }
    return Success(data=data)

@router.post("/restart", summary="重启进程")
async def restart_task(task_name: str = Query(..., description="进程name")):
    if task_name not in task_manager.tasks:
        raise HTTPException(status_code=404, detail="任务不存在")

    result = await task_manager.restart_task(task_name)
    data = {
        "task_name": task_name,
        "status": "已重启" if result else "重启失败",
        "current_status": task_manager.tasks[task_name].status
    }
    return Success(data=data)
